package chaowan.Controller;
import chaowan.Service.ShopUserService;
import chaowan.pojo.ShopUser;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.List;
@Controller
@RequestMapping("/user")
public class ShopUserController {

    @Resource
    private ShopUserService shopUserService;
@GetMapping("/login")
public String loginForm() {
    return "user/login";
}

@PostMapping("/login")
public String login(@RequestParam String uname, @RequestParam String pwd, HttpSession session, Model model) {
    ShopUser user = shopUserService.login(uname, pwd);
    if (user != null) {
        session.setAttribute("loginUser", user);

        if ("管理员".equals(user.getType())) {
            return "redirect:/goods/list";
        } else if ("普通用户".equals(user.getType())) {
            return "redirect:/goods/frontList";
        } else {
            model.addAttribute("errorMsg", "未知用户类型");
            return "user/login";
        }

    } else {
        model.addAttribute("errorMsg", "用户名或密码错误");
        return "user/login";
    }
}
@GetMapping("/register")
public String registerForm() {
    return "user/register";
}

@PostMapping("/register")
public String register(ShopUser user, Model model) {
    // 判断用户名是否存在（不要插入）
    ShopUser existingUser = shopUserService.findByUsername(user.getUname());
    if (existingUser != null) {
        model.addAttribute("errorMsg", "用户名已存在");
        return "user/register";
    }

    // 设置默认值
    user.setType("普通用户");
    user.setActive(1);
    user.setCreatedAt(new Date());

    // 插入
    shopUserService.save(user);
    return "redirect:/user/login";
}

@GetMapping("/logout")
public String logout(HttpSession session) {
    session.invalidate();
    return "redirect:/user/login";
}
@PostMapping("/update")
    public String update(ShopUser shopUser) {
        shopUserService.update(shopUser);
        return "redirect:/user/list";
    }

    @GetMapping("/delete/{uid}")
    public String deleteUser(@PathVariable Integer uid, Model model) {
        try {
            shopUserService.deleteById(Long.valueOf(uid));
        } catch (RuntimeException e) {
            model.addAttribute("errorMessage", e.getMessage());
            model.addAttribute("userList", shopUserService.getAllUsers());
            return "user/list"; 
        }
        return "redirect:/user/list";  
    }
}
}